/*
 * Copyright (C) 2013 The original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.zapta.apps.maniana.model;

import java.util.Calendar;
import java.util.GregorianCalendar;

import com.zapta.apps.maniana.annotations.ApplicationScope;
import com.zapta.apps.maniana.model.ItemRepeat;
import com.zapta.apps.maniana.model.ItemRepeatReadOnly;
import com.zapta.apps.maniana.model.ItemRepeatDayReadOnly;

/**
 * Represents the data on when an item should repeat (day or count of days)
 *
 * @author Elliott Mitchell
 */

@ApplicationScope
public class ItemRepeatDay extends ItemRepeat implements ItemRepeatDayReadOnly {
	/** Run on a fixed schedule, not after the previous completion */
	private boolean mIsFixed;

	/** Number of days to add each time */
	private short mRepeatDays;

	public ItemRepeatDay() {
		super();
	}

	public ItemRepeatDay(ItemRepeatDayReadOnly other) {
		super(other);
		mIsFixed=other.getIsFixed();
		mRepeatDays=(short)(other.getRepeatDays()-1);
	}

	public ItemRepeatDay(ItemModel.StoreIF IF) {
		super(IF);
	}

	@Override
	public ItemRepeatType getType() {
		return ItemRepeatType.DAY;
	}

	@Override
	public boolean getIsFixed() {
		return mIsFixed;
	}
	public void setIsFixed(boolean isFixed) {
		mIsFixed = isFixed;
	}

	@Override
	public int getRepeatDays() {
		return (mRepeatDays&0xFFFF)+1;
	}
	public void setRepeatDays(int repeatDays) {
		mRepeatDays=(short)(repeatDays-1);
	}

	@Override
	public void fromStore(ItemModel.StoreIF IF) {
		super.fromStore(IF, "day");
		mIsFixed=IF.getBoolean("repeat_day_fixed");
		mRepeatDays=IF.getShort("repeat_days");
	}

	@Override
	public void toStore(ItemModel.StoreIF IF) {
		super.toStore(IF);
		IF.setString("repeat_type", "day");
		if(mIsFixed) IF.setBoolean("repeat_day_fixed", true);
		if(mRepeatDays!=0) IF.setShort("repeat_days", mRepeatDays);
	}

	@Override
	public boolean checkDelete(ItemModel item) {
		final int old;
		if(mIsFixed) old=item.getDueDate();
		else old=item.getCompletionDate();

		final Calendar cal=new GregorianCalendar(
(old>>>ItemModel.SHIFT_YEAR)&ItemModel.MASK_YEAR,
(old>>>ItemModel.SHIFT_MONTH)&ItemModel.MASK_MONTH,
(old>>>ItemModel.SHIFT_DAY)&ItemModel.MASK_DAY);

		cal.add(Calendar.DAY_OF_YEAR, (mRepeatDays&0xFFFF)+1);

		final int next=(cal.get(Calendar.YEAR)<<ItemModel.SHIFT_YEAR)|
(cal.get(Calendar.MONTH)<<ItemModel.SHIFT_MONTH)|
(cal.get(Calendar.DAY_OF_MONTH)<<ItemModel.SHIFT_DAY);

		return super.checkDelete(item, next);
	}
}

